<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/3/12
 * Time: 1:34 下午
 */

namespace app\common\lib\mini\wechat;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Cache;
use think\Env;

/**
 * 微信小程序相关接口
 * Class subscribeMessage
 */
class WechatMini
{
    protected $appId = 'wx13aa45fb16ed9635';
    protected $appSecret = '7c09934c7ec7a45433410337ff935b25';

    /**
     * 获取接口调用凭证
     * @return mixed
     * @throws ApiException
     */
    protected function getAccessToken()
    {
        $access_token = Cache::get('mini_msg_token');
        if (!$access_token)
        {
            $tokenInfo = Util::curlRequest('GET', "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}");
            if ($tokenInfo)
            {
                $tokenInfo = json_decode($tokenInfo, true);
            }
            if (isset($tokenInfo['errcode']) && $tokenInfo['errcode'] !== 0)
            {
                throw new ApiException('微信小程序获取token失败:' . $tokenInfo['errmsg']);
            }
            $access_token = $tokenInfo['access_token'];
            Cache::set('mini_msg_token', $access_token, $tokenInfo['expires_in']);
        }
        return $access_token;
    }

    /**
     * 发送订阅消息
     * @param $openid
     * @param $data
     * @param string $template_id
     * @param string $page
     * @return bool
     * @throws ApiException
     */
    public function subscribeMessage($openid, $data, $template_id = '', $page = 'index?foo=bar')
    {
        $param = [
            'access_token' => $this->getAccessToken(),
            'touser' => $openid,//接收者（用户）的 openid
            'template_id' => $template_id,//所需下发的订阅模板id
            'page' => $page,//示例index?foo=bar
            'data' => json_encode($data, true),//{ "key1": { "value": any }, "key2": { "value": any } }
            'miniprogram_state' => Env::get('wechat_backup_07_18_14_43_00.miniprogram_state'),
            'lang' => 'zh_CN',//zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN
        ];
        $res = Util::curlRequest('POST', 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send', $param);
        if ($res)
        {
            $res = json_decode($res, true);
        }
        if (isset($res['errcode']) && $res['errcode'] !== 0)
        {
            throw new ApiException('微信小程序发送订阅消息失败:' . $res['errmsg']);
        }
        return true;
    }
}
